import router from './router'
import store from './store'
import { Loading } from 'element-ui'

import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
const whiteList = ['login']
var loadingInstance = null
function startLoading() {
  loadingInstance = Loading.service({
    fullscreen: true,
    text: '页面渲染中...',
    customClass: 'common-loading'
  })
}
function endLoading() {
  if (loadingInstance) {
    loadingInstance.close()
  }
}
router.beforeEach(async(to, from, next) => {
  startLoading()
  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      endLoading()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          const { roles } = await store.dispatch('getInfo')

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          console.error(error)
          await store.dispatch('resetToken')
          next(`/login?redirect=${to.path}`)
          endLoading()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.name) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      endLoading()
    }
  }
})

router.afterEach(() => {
  endLoading()
})
